package main

import (
	"flag"
	"fmt"
	"os"

	_ "userver/gate/ctrl" // import on demand
	//
	_ "userver/gate/apis/demo" // import on demand

	"gitee.com/cloudapex/ulern/cto"
	"gitee.com/cloudapex/ulern/util"
	"github.com/kardianos/service"
)

const (
	DEF_APP_MAJOR  = 1      // 主版本号
	DEF_APP_MINOR  = 0      // 次版本号
	DEF_APP_REVISE = 1      // 修订版本号
	DEF_APP_NAME   = "gate" // 应用名称
	DEF_APP_TITLE  = "网关服务" // 应用显示名称
)

var logConf util.LogConf
var ver = fmt.Sprintf("%d.%d.%d", DEF_APP_MAJOR, DEF_APP_MINOR, DEF_APP_REVISE)

func init() {
	flag.IntVar((*int)(&logConf.Level), "logLv", int(util.ELL_Debug), "Main logger level[1:LL_DEBUG]")
	flag.IntVar((*int)(&logConf.OutMode), "logMode", int(util.ELM_Std), "Main logger outMode[std|file]")
	flag.StringVar(&logConf.DirName, "logDir", "./logs", "Main log dir name[logs]")
	flag.StringVar(&logConf.FileName, "logFile", "", "Main log file name[same as exe]")
	flag.StringVar(&logConf.FileSuffix, "logSuffix", "", "Main log file suffix[log]")
}

type program struct{}

func (p *program) Init() bool {
	if len(os.Args) > 1 && (os.Args[1] == "-I" || os.Args[1] == "-U" || os.Args[1] == "-S") {
		svcConfig := &service.Config{
			Name:        DEF_APP_NAME,                                                           //服务显示名称
			DisplayName: DEF_APP_TITLE,                                                          //服务名称
			Description: fmt.Sprintf("This is an YuXue %s server of Go service.", DEF_APP_NAME), //服务描述
			Arguments:   []string{"-S", "-logLv=2", "-logMode=2"},
		}

		s, err := service.New(&program{}, svcConfig)
		if err != nil {
			util.Print("err:%v", err)
			return false
		}

		switch os.Args[1] {
		case "-I":
			if err = s.Install(); err != nil {
				util.Print("Service Installation err:%v.", err)
			} else {
				util.Print("Service Installation successful.")
			}
		case "-U":
			if err = s.Uninstall(); err != nil {
				util.Print("Service Installation err:%v.", err)
			} else {
				util.Print("Service uninstallation successful.")
			}
		case "-S":
			if err = s.Run(); err != nil {
				util.Print("Service Run err:%v", err)
			}
		}
		return false
	}
	return true
}
func (p *program) Start(s service.Service) error {
	go p.Work()
	return nil
}
func (p *program) Stop(s service.Service) error {
	util.Quit()
	return nil
}
func (p *program) Work() {
	cto.Init(DEF_APP_NAME, &logConf)

	cto.Report(util.ELL_Error, nil)

	defer func() { util.Catch("Main", recover(), true) }()

	if err := cto.Work(); err != nil {
		util.Log.Fatal("Start Work error:%q.", err)
	}

	cto.Wait()
}

func main() {
	if prg := (&program{}); prg.Init() {
		prg.Work()
	}
}
